/*

  The MIT License, 

  Copyright (c) 2011. Dimarik

*/
package
{

import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;
import flash.system.LoaderContext;
import flash.system.Security;
import flash.system.SecurityDomain;

import substitutionTestClasses.BaseClass;

/**
 *  @author				Dimarik
 *  @version			1.2
 *  @langversion		3.0
 *  @playerversion		9.0
 * 
 */
[SWF(width="800", height="600", frameRate="21", backgroundColor="#E0EEEE")]

public class ClassSubstitutionTest extends Sprite {

	//-------------------------------------------------------------------------
	//
	//   Private variables
	//
	//-------------------------------------------------------------------------

	/**
	 * @private 
	 */	
	private static const IS_REMOTE:Boolean = Security.sandboxType == Security.REMOTE;

	//-------------------------------------------------------------------------
	//
	//   Constructor
	//
	//-------------------------------------------------------------------------

	public function ClassSubstitutionTest() {
		super();
		super.addEventListener(Event.ADDED_TO_STAGE, this.creationComplete);
	}

	//-------------------------------------------------------------------------
	//
	//   Private methods
	//
	//-------------------------------------------------------------------------

	private function creationComplete(event:Event):void {
		super.removeEventListener(event.type, arguments.callee);
		const loader:Loader = new Loader();
		const li:LoaderInfo = loader.contentLoaderInfo;
		li.addEventListener(Event.COMPLETE, this.handler_complete, false, int.MAX_VALUE);
		li.addEventListener(Event.COMPLETE, this.handler_publicComplete);
		loader.load( new URLRequest('http://socfoot.terrhq.ru/LoadeeSubstitutionClass.swf?'+(new Date().getTime()) ) );
		//loader.load( new URLRequest('LoadeeSubstitutionClass.swf'));
	}

	//-------------------------------------------------------------------------
	//
	//   Event handlers
	//
	//-------------------------------------------------------------------------

	/**
	 * @private 
	 * Основной обработчик
	 */
	private function handler_publicComplete(event:Event):void {
		const li:LoaderInfo = event.target as LoaderInfo;
		li.removeEventListener(Event.COMPLETE, arguments.callee);
		const test:BaseClass = li.content as BaseClass;
		test.test();
	}

	/**
	 * @private 
	 * Вспомогательный обработчик
	 */	
	private function handler_complete(event:Event):void {
		const li:LoaderInfo = event.target as LoaderInfo;
		li.removeEventListener(Event.COMPLETE, arguments.callee);

		if (
			   !(li.sameDomain || IS_REMOTE)	// Локальный лоадер загружает удаленный ролик.
			|| !li.childAllowsParent			// У loadee нет разрешения создателя.
		) {
			event.stopImmediatePropagation();
			li.loader.loadBytes(li.bytes);
		}

	}

}
}
